<template>
  <div class="forward">
    <div class="forward-top">
      <div>
        <el-select :disabled="walletIncome_loading||walletWithdrawal_loading" v-model="type" :placeholder="$t('dashboard.selector')">
          <el-option v-for="(v,k) in options" :key="k" :label="k" :value="k">
          </el-option>
        </el-select>
      </div>
      <div class="info">
        <div class="item">{{$t('dashboard.earn')}} <spinner v-if="walletIncome_loading"/> <template v-else><cu :val="all_money | divided8" :decimals="8"></cu> {{type}}</template></div>
        <div class="item">{{$t('wallet.walletCount.all_income')}} <spinner v-if="walletIncome_loading"/> <template v-else><cu :val="frozen_money | divided8" :decimals="8"></cu> {{type}}</template></div>
        <div class="item">{{$t('wallet.forward.available_balance')}} <spinner v-if="walletIncome_loading"/> <template v-else><cu :val="money | divided8" :decimals="8"></cu> {{type}}</template></div>
      </div>
    </div>
    <div class="forward-content">
      <p class="title">{{type}}{{$t('wallet.forward.address')}}</p>
      <el-select :disabled="inviteAddress_loading||walletWithdrawal_loading" v-model="address" :placeholder="$t('wallet.forward.address_select_info')">
        <el-option v-for="(v,k) in addressList" :key="k" :label="v.name+'-'+ v.address" :value="v.address">
          </el-option>
      </el-select>
      <p class="title" style="margin-top:28px;">{{$t('wallet.forward.reflect')}}
        <span class="count">[{{$t('wallet.forward.available_balance')}} <spinner v-if="walletIncome_loading"/> <template v-else><cu :val="money | divided8" :decimals="8"></cu> {{type}}</template>]<div class="tishi" v-if="amountInfo">{{amountInfo}}</div></span>
      </p>
      <div class="input-box" :class="{disabled:walletWithdrawal_loading}">
        <input type="text" v-model="amount" :disabled="walletWithdrawal_loading" :placeholder="$t('wallet.forward.walletWithdrawal')+options[type].min.toFixed(8)+' '+type">
        <span>{{type}}</span>
      </div>
      <p class="fee">
        <span>{{$t('wallet.forward.actual')}} {{(actual_fee).toFixed(8)}}</span>
        <span>{{$t('wallet.bill.serviceCharge')}} {{options[type].fee}}</span>
      </p>
      <button :disabled="walletIncome_loading||inviteAddress_loading||walletWithdrawal_loading" @click="submit">
        <i v-if="walletWithdrawal_loading" class="el-icon-loading"></i>
        <template v-else>{{$t('btn.submit')}}</template>
      </button>
      <p class="tips">{{$t('wallet.forward.reminder')}}</p>
      <p class="tips-con">
        <template v-if="language === 'zh'">
          <span>{{$t('wallet.forward.reminder1')}}<router-link :to="'/wallet/bill?type='+this.type.toLowerCase()"> {{$t('wallet.forward.reminder2')}} </router-link>{{$t('wallet.forward.reminder3')}}</span>
        </template>
        <template v-else>
          <span>{{$t('wallet.forward.reminder1')}}{{$t('wallet.forward.reminder2')}} <router-link :to="'/wallet/bill?type='+this.type.toLowerCase()"> {{$t('wallet.forward.reminder3')}} </router-link></span>
        </template>
      </p>
    </div>
    <el-dialog class="email" :visible.sync="dialogVisible" width="30%" @closed="$router.push('/wallet/walletlist')">
      <p class="title">{{$t('wallet.forward.forward_success')}}</p>
      <p class="count">{{parseFloat(amount).toFixed(8)}}{{type}}</p>
      <p class="tishi">{{$t('wallet.forward.two_days')}}</p>
      <p class="name">{{$t('wallet.forward.receivables')}}</p>
      <p class="adress">{{address}}</p>
      <div class="button" @click="dialogVisible = false">{{$t('btn.submit')}}</div>
    </el-dialog>
  </div>
</template>
<script>
import { walletIncome, inviteAddress, walletWithdrawal } from '@/api';
import pagination from '@/components/Pagination';
import cu from '@/components/CountUp';
import spinner from '@/components/Spinner';
import { mapGetters } from 'vuex';

export default {
  components: { pagination, spinner, cu },
  data() {
    return {
      options: {
        BTC: {
          fee: 0.00001, // 手续费
          min: 0.01, // 最小提现数量
        },
        ZEC: {
          fee: 0.005, // 手续费
          min: 0.1, // 最小提现数量
        },
        // BUC: {
        //   fee: 0,
        //   min: 100,
        // },
        // MUT: {
        //   fee: 0,
        //   min: 100,
        // },
      },
      amount: 0,
      amountInfo: '',
      dialogVisible: false,
      walletIncome_loading: false,
      inviteAddress_loading: false,
      walletWithdrawal_loading: false,
      type: '',
      address: '',
      all_money: 0,
      frozen_money: 0,
      money: 0,
      page: 1,
      addressList: [],
    };
  },
  beforeCreate() {
    if (this.$route.query.type === 'buc' || this.$route.query.type === 'mut') {
      this.$router.push('/404');
    }
  },
  computed: {
    ...mapGetters(['id', 'language']),
    actual_fee() {
      return (this.amountInfo || !this.amount) ? 0 : this.amount - this.options[this.type].fee;
    },
  },
  created() {
    this.type = (this.$route.query.type || 'BTC').toUpperCase();
  },
  methods: {
    submit() {
      this.vAmount();
      if (this.amountInfo) {
        return;
      }
      if (!this.address) {
        return;
      }
      this.walletWithdrawal_loading = true;
      walletWithdrawal({
        parent_uid: this.id,
        amount: this.amount,
        unit: this.type,
        address: this.address }).then((res) => {
        if (res.data.status === 1) {
          this.dialogVisible = true;
        } else {
          this.$message.error(this.$t(`api.${res.data.errcode}`));
        }
        this.walletWithdrawal_loading = false;
      }).catch(() => {
        this.walletWithdrawal_loading = false;
        this.$message.error(this.$t('error.catchError'));
      });
    },
    walletIncome() {
      this.walletIncome_loading = true;
      this.address = '';
      walletIncome({ parent_uid: this.id }).then((res) => {
        if (res.data.status === 1) {
          const dataType = res.data.data[this.type.toLowerCase()];
          if (!dataType) {
            this.all_money = 0;
            this.frozen_money = 0;
            this.money = 0;
            this.walletIncome_loading = false;
            return;
          }
          this.all_money = dataType.all_money;
          this.frozen_money = dataType.frozen_money;
          this.money = dataType.money;
        } else {
          this.$message.error(this.$t(`api.${res.data.errcode}`));
        }
        this.walletIncome_loading = false;
      }).catch(() => {
        this.walletIncome_loading = false;
        this.$message.error(this.$t('error.catchError'));
      });
    },
    loopInviteAddress() {
      // promise 递归请求提现地址
      const limit = 1000;
      return inviteAddress(
        {
          parent_uid: this.id,
          page: this.page,
          limit,
        }).then((res) => {
        if (res.data.status === 1) {
          if (res.data.data.length < limit) {
            return res.data.data;
          }
          this.page += 1;
          return this.loopInviteAddress().then(nextData => [].concat(res.data.data, nextData));
        }
        return Promise.reject(res.data.msg);
      });
    },
    inviteAddress() {
      this.inviteAddress_loading = true;
      this.loopInviteAddress().then((list) => {
        this.addressList = list.filter(v => v.type === this.type.toLowerCase());
        this.address = this.addressList[0] ? this.addressList[0].address : '';
        this.inviteAddress_loading = false;
      }).catch((err) => {
        if (typeof err === 'string') {
          // res.data.msg !== 1;
          this.$message.error(err);
        } else {
          this.$message.error(this.$t('error.catchError'));
        }
        this.inviteAddress_loading = false;
      });
    },
    vAmount() {
      this.amount = this.amount.toString().replace(/[^\d/^.]/g, '');
      const money = (this.money || 0) / 100000000;
      if (!this.amount.toString()) {
        this.amountInfo = this.$t('wallet.forward.num_sure');
        return;
      }
      // 首位补0
      if (this.amount.toString()[0] === '.') {
        this.amount = `0${this.amount}`;
      }
      // 去除第二个小数点
      const arr = this.amount.toString().split('.');
      if (arr.length > 2) {
        this.amount = `${arr[0]}.${arr[1]}`;
      }
      // 不能超过余额
      if (this.amount > money) {
        this.amount = money;
        this.amountInfo = '';
        return;
      }
      // 不能低于限制
      if (this.amount < this.options[this.type].min) {
        this.amountInfo = `${this.$t('wallet.forward.last')}${this.options[this.type].min.toFixed(8)} ${this.type}`;
        return;
      }
      this.amountInfo = '';
    },
  },
  watch: {
    amount() {
      this.vAmount();
    },
    type() {
      this.amount = 0;
      this.amountInfo = ''; // 清空错误提示
      this.address = ''; // 选择第一个地址
      this.page = 1;
      this.walletIncome();
      this.inviteAddress();
    },
  },
};
</script>
<style scoped lang="scss">
.forward {
  > div {
    box-sizing: border-box;
  }

  .email {
    .title {
      height: 40px;
      line-height: 40px;
      text-align: left;
      color: #323232;
      font-size: 16px;
      padding-left: 15px;
      box-sizing: border-box;
      background-color: #eeeeee;
    }
    .count {
      font-size: 20px;
      color: #70c1b3;
      text-align: center;
      margin-top: 30px;
    }
    .tishi {
      font-size: 14px;
      text-align: center;
      color: #565656;
      margin-top: 15px;
    }
    .name {
      text-align: center;
      font-size: 14px;
      color: silver;
      margin-top: 20px;
    }
    .adress {
      text-align: center;
      font-size: 12px;
      color: #565656;
    }
    .button {
      margin: 0 auto;
      margin-top: 30px;
      height: 40px;
      line-height: 40px;
      width: 180px;
      background-color: #70c1b3;
      color: #ffffff;
      border-radius: 5px;
      cursor: pointer;
    }
  }
  .fee {
    overflow: hidden;
    font-size: 14px;
    color: #247ba0;
    text-align: right;
    margin-top: 20px;
    span {
      float: right;
      margin-left: 30px;
    }
  }
  .tips {
    margin-top: 50px;
    font-size: 18px;
    color: #c33751;
    text-align: left;
  }
  .tips-con {
    text-align: left;
    span {
      position: relative;
      padding-left: 20px;
      font-size: 14px;
      color: #565656;
      a {
        font-style: normal;
        color: #70c1b3;
        cursor: pointer;
      }
      &::before {
        position: absolute;
        top: 50%;
        margin-top: -2px;
        left: 7px;
        content: " ";
        width: 4px;
        height: 4px;
        border-radius: 50%;
        background-color: #eb547c;
      }
    }
  }
  input::-webkit-input-placeholder,
  textarea::-webkit-input-placeholder {
    /* WebKit browsers */
    color: rgb(179, 179, 179);
  }
  input:-moz-placeholder,
  textarea:-moz-placeholder {
    /* Mozilla Firefox 4 to 18 */
    color: rgb(179, 179, 179);
  }
  input::-moz-placeholder,
  textarea::-moz-placeholder {
    /* Mozilla Firefox 19+ */
    color: rgb(179, 179, 179);
  }
  input:-ms-input-placeholder,
  textarea:-ms-input-placeholder {
    /* Internet Explorer 10+ */
    color: rgb(179, 179, 179);
  }
  .forward-top {
    border: solid 1px #e0e0e0;
    border-radius: 5px;
    overflow: hidden;
    > div {
      padding: 25px 60px;
      box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.05);
      background-color: #ffffff;
    }

    .info {
      padding: 10px 60px;
      background-color: #f9f9f9;
      height: 55px;
      line-height: 55px;
      display: flex;
      justify-content: space-between;
      .item {
        position: relative;
        padding-left: 48px;
        width: 218px;
        height: 34px;
        line-height: 34px;
        box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.05);
        border-radius: 4px;
        color: #565656;
        text-align: left;
        font-size: 14px;
        border: solid 1px #70c1b3;
        box-sizing: border-box;
        &::before {
          content: "";
          display: block;
          width: 20px;
          height: 20px;
          background-color: red;
          border-radius: 50%;
          position: absolute;
          top: 50%;
          left: 19px;
          margin-top: -10px;
        }
        &:nth-child(1)::before {
          background: url(../../assets/images/wallet-tixian-item3.png) #70c1b3
            center no-repeat;
        }
        &:nth-child(2)::before {
          background: url(../../assets/images/wallet-tixian-item1.png) #f7cc86
            center no-repeat;
        }
        &:nth-child(3){
          width: 248px;
          &::before {
          background: url(../../assets/images/wallet-tixian-item2.png) #b2dbbf
            center no-repeat;
        }
        }
      }
    }
  }
  .forward-content {
    margin-top: 10px;
    padding: 50px 60px 0;
    box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.05);
    border: solid 1px #e0e0e0;
    background-color: #ffffff;
    padding-bottom: 20px;
    button {
      width: 200px;
      height: 50px;
      font-size: 22px;
      border-radius: 5px;
      color: #ffffff;
      border: none;
      background-color: #70c1b3;
      margin-top: 82px;
      outline: none;
      &:disabled{
        cursor: not-allowed;
      }
    }
    > .title {
      font-size: 22px;
      color: #70c1b3;
      line-height: 38px;
      text-align: left;
      .count {
        font-size: 14px;
        color: #247ba0;
        margin-left: 5px;
        position: relative;
        .tishi {
          position: absolute;
          top: 4px;
          right: 0;
          transform: translateX(120%);
          padding: 0 6px;
          border-radius: 2px;
          line-height: 18px;
          height: 18px;
          background-color: #eb547c;
          color: #fff;
          font-size: 12px;
          white-space: nowrap;
          &::before {
            content: " ";
            position: absolute;
            top: 13px;
            left: -2px;
            transform: rotate(24deg);
            border: 6px solid #eb547c;
            border-bottom-color: transparent;
            border-right-color: transparent;
          }
        }
      }
    }
    .input-box {
      height: 50px;
      width: 100%;
      box-shadow: 0px 0px 5px 0px rgba(0, 130, 108, 0.05);
      border-radius: 5px;
      border: solid 1px #b2dbbf;
      // overflow: hidden;
      position: relative;
      &.disabled{
        background-color: #f5f7fa;
        color: #c0c4cc;
      }
      input {
        width: 720px;
        height: 48px;
        line-height: 50px;
        font-size: 14px;
        border-radius: 5px;
        color: #323232;
        padding-left: 10px;
        box-sizing: border-box;
        float: left;
        border: none;
        outline: none;
        &:disabled{
          background-color: #f5f7fa;
          color: #c0c4cc;
        }
      }
      span {
        display: block;
        width: 84px;
        height: 18px;
        line-height: 20px;
        border-left: 2px solid #b2dbbf;
        text-align: center;
        float: right;
        margin-top: 16px;
      }
    }
  }
}
</style>
